package com.xuecheng.content.service.impl;

import cn.hutool.core.io.IoUtil;
import com.xuecheng.content.config.MinioTemplate;
import com.xuecheng.content.domain.CoursePub;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @Author 12441
 * @Date 2022/9/21 15:33
 * @Version 1.0
 */
// 课程发布 freemarker + minio
@Service
public class AsyncCoursePubService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioTemplate minioTemplate;
    @Async
    public void publish(Map map, CoursePub coursePub) throws IOException, TemplateException {
        //优化用户体验，去除点击发布时等待静态页面生成等待的空闲-开启异步
        System.out.println(">>>>>>>>>>>>开启异步");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //--------------------------------Minio上传静态页面代码-------------------------------------------
        //7.freemarker生成静态页
        //7-1.获取模板
        Template template = configuration.getTemplate("learing_article.ftl");
        //7-2.模型+模板=输出
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //7-3.将html文本内容转成io流
        ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(content.getBytes());

        //8.保存到Minio
        minioTemplate.uploadHTML(byteArrayInputStream, coursePub.getId()+".html");

    }
}
